package com.cwf.security.filter;

import com.alibaba.fastjson2.JSON;
import com.cwf.common.entity.auth.TokenInfo;
import com.cwf.common.enums.TokenInfoKeyEnum;
import com.cwf.common.utils.auth.JwtUtil;
import com.cwf.security.entity.SecurityUser;
import com.cwf.security.entity.User;
import com.cwf.security.entity.UserLogin;
import com.cwf.security.service.RedisPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    AuthenticationManager authenticationManager;


    @Autowired
    RedisPermissionService redisPermissionService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        System.out.println(token);

        TokenInfo userInfo = JwtUtil.getTokenInfo(token, TokenInfoKeyEnum.OK.getCode());

        UserLogin user = new UserLogin();
        Optional.ofNullable(userInfo.getUserId()).ifPresent(v -> {

            System.out.println(userInfo.getUserId());
            List<String> permissionList = redisPermissionService.getPermission(userInfo.getUserId());

            log.info("\nredis缓存权限:{}\n", redisPermissionService.getPermission(userInfo.getUserId()));


            SecurityUser loginUser = new SecurityUser(user, permissionList, null);

            Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();

            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(user, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        });

        filterChain.doFilter(request, response);

    }
}
